package com.sensePlusVR.utils;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

public class SslHttps {
	
	private static final String TAG="SslHttps";
	
	@SuppressLint("TrulyRandom")
	public static SSLContext getSSLContext(Context context) {  
        
        CertificateFactory certificateFactory = null;  
        InputStream inputStream = null;  
        Certificate cer = null;  
        KeyStore keystore = null;  
        TrustManagerFactory trustManagerFactory = null;
        Log.e(TAG, "xxxxxxxxxxxxxxxxx");
        try {  
              
            certificateFactory = CertificateFactory.getInstance("X.509");  
            inputStream = context.getAssets().open("senselovers.cer");//这里导入SSL证书文件  
              
            try {  
                //读取证书  
                cer = certificateFactory.generateCertificate(inputStream);  
                Log.d(TAG, cer.getPublicKey().toString());  
                  
            } finally {
            	Log.d(TAG, "load cer file error"); 
                inputStream.close();  
            }  
  
            //创建一个证书库，并将证书导入证书库  
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());  
            keystore.load(null,null); //双向验证时使用  
            keystore.setCertificateEntry("trust", cer);  
              
            // 实例化信任库  
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());  
            // 初始化信任库  
            trustManagerFactory.init(keystore);  
  
            SSLContext s_sSLContext = SSLContext.getInstance("TLS");  
            s_sSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());  
              
           //信任所有证书 （官方不推荐使用）  
//         s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {   
//                
//              @Override  
//              public X509Certificate[] getAcceptedIssuers() {  
//                  return null;  
//              }  
//                
//              @Override  
//              public void checkServerTrusted(X509Certificate[] arg0, String arg1)  
//                      throws CertificateException {  
//                    
//              }  
//                
//              @Override  
//              public void checkClientTrusted(X509Certificate[] arg0, String arg1)  
//                      throws CertificateException {  
//                    
//              }  
//          }}, new SecureRandom());  
              
            return s_sSLContext;  
              
        } catch (Exception e) {
        	Log.d(TAG, e.getMessage());
            //e.printStackTrace();  
        }  
        return null;  
    }  
}
